<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'employees_export'" type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button
            v-allow="'addEmployee'"
            type="primary"
            size="small"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'timeOfEntry', order: 'descending'}">
          <el-table-column label="序号" type="index" width="50" />
          <el-table-column label="姓名" prop="username" />
          <!-- 图像 -->
          <el-table-column label="图像" prop="staffPhoto" width="100">
            <!-- 图像 -->
            <template #default="{row}">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                style="width:100%"
                @click="imgs(row.staffPhoto)"
              >
            </template>
          </el-table-column>

          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ HhireType(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hcurId(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="belEsit(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            :page-size="size"
            :current-page="page"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 弹层组件 -->
      <el-dialog
        title="新增"
        :visible.sync="showDialog"
        width="40%"
      >
        <AddDialog v-if="showDialog" @success="Hsuccess" />
      </el-dialog>

      <!-- 二维码弹层 -->
      <el-dialog
        title="二维码弹"
        :visible.sync="showCodeDialog"
        width="40%"
      >
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>

      <!-- 分配角色弹层 -->
      <el-dialog
        title="分配角色"
        :visible.sync="assignDialog"
        width="40%"
      >
        <AssignRole
          v-if="assignDialog"
          :cur-id="curId"
          @success="assignDialog = false"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployees, deleteEmployees } from '@/api/employees'
import AssignRole from './assignRole'
var QRCode = require('qrcode')
import AddDialog from './empDialog.vue'
// 导入枚举文件
import employees from '@/constant/employees'
const hireType = {}
employees.hireType.forEach(item => {
  hireType[item.id] = item.value
})

export default {
  name: 'VueWhZr3Employees',
  components: {
    AddDialog,
    AssignRole
  },

  data() {
    return {
      list: [], // 员工列表
      page: 1, // 页码值
      size: 5, // 每页显示几条数据
      total: 0, // 总条数
      showDialog: false, // 弹层的显示或隐藏
      showCodeDialog: false, // 二维码弹层
      assignDialog: false, // 分配角色弹层
      curId: ''
    }
  },

  created() {
    this.lodeEmployees()
  },

  methods: {
    hcurId(id) {
      this.assignDialog = true
      this.curId = id
    },
    // 二维码
    imgs(url) {
      if (url) {
        this.showCodeDialog = true // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QRCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })
      }
    },
    // 核心实现导出的代码
    handleDownload() {
      // import('@/vendor/Export2Excel')  懒加载的方式导入一个模块， 返回值是一个promise实例
      import('@/vendor/Export2Excel').then(excel => {
        const { data, Header } = this.enZhuanZ(this.list)

        excel.export_json_to_excel({
          header: Header,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        // console.log(tHeader, data)
      })
    },
    // 数据转换函数
    enZhuanZ(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      const one = list[0]
      if (!one) return
      const Header = Object.keys(one).map(item => {
        return mapInfo[item]
      })

      const data = list.map(item => {
        return Object.values(item)
      })

      return { data, Header }
    },
    // 新增
    Hsuccess() {
      this.showDialog = false
      this.tota++
      const max = Math.ceil(this.total / this.size)
      this.page = max
      this.lodeEmployees()
    },
    // 删除
    async belEsit(id) {
      this.$confirm('你确定要删除吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await deleteEmployees(id)
        //   // console.log(res)
        if (res.code === 10000) {
          if (this.list.length === 1) {
            this.page--
            if (this.page <= 0) {
              this.page = 1
            }
          }
          // 删除成功后重新获取数据并渲染
          this.lodeEmployees()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    HhireType(id) {
      return hireType[id] || '未知'
    },
    // 获取员工列表
    async lodeEmployees() {
      try {
        const res = await getEmployees({ page: this.page, size: this.size })
        // console.log(res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    },
    // 当页码值发生变化时就会执行
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.lodeEmployees()
    }
  }
}
</script>

<style lang="
          scss"
          scoped
          @error="assignDialog = false"
        >

</style>

